package com.tianma.upload.uploadjartest.socket.udp.demo02;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author lgc
 * @createDate 2020/8/18 - 9:17
 */
public class TalkReceive implements Runnable {
    private DatagramSocket socket;
    private Integer myPort;

    public TalkReceive(Integer myPort) {
        this.myPort = myPort;
        try {
            socket=new DatagramSocket(myPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
            try {
                socket.receive(datagramPacket);
                System.out.println(datagramPacket.getAddress());
                String s = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
                System.out.println(s);
                if ("bye".equals(s)){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
